package org.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.dingtalk.open.app.api.OpenDingTalkClient;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.callback.OpenDingTalkCallbackListener;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 王姐AI
 */
@Slf4j
public class SendGroupMessage {
    private String clientId = "钉钉cid";
    private String clientSecret = "钉钉cs";

    public void start() throws Exception {
        OpenDingTalkClient client = OpenDingTalkStreamClientBuilder
                .custom()
                .credential(new AuthClientCredential(clientId, clientSecret))
                .registerCallbackListener("/v1.0/im/bot/messages/get", new RobotMsgCallbackConsumer())
                .build();
        client.start();
    }

    public class RobotMsgCallbackConsumer implements OpenDingTalkCallbackListener<JSONObject, JSONObject> {

        @Override
        public JSONObject execute(JSONObject request) {
            String userId = request.get("senderStaffId").toString();
            String content = request.getJSONObject("text").getString("content");
            String openConversationId = request.get("conversationId").toString();
            String robotCode = request.get("robotCode").toString();
            log.info("王姐收到消息：={}, msg={},openConversationId={},robotCode={} ", userId, content, openConversationId, robotCode);

            OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
            orgGroupSendHeaders.setXAcsDingtalkAccessToken(getToken());

            OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();
            orgGroupSendRequest.setMsgKey("sampleText");
            orgGroupSendRequest.setRobotCode(robotCode);

            orgGroupSendRequest.setOpenConversationId(openConversationId);

            JSONObject msgParam = new JSONObject();
            msgParam.put("content", content);
            HttpResponse<String> response = Unirest.post("https://api.siliconflow.cn/v1/chat/completions")
                    .header("Authorization", "Bearer 你的模型token")
                    .header("Content-Type", "application/json")
                    .body("{\n    " +
                            "\"model\": \"deepseek-ai/DeepSeek-V3\",\n    " +
                            "\"messages\": [\n        {\n            " +
                            "\"role\": \"system\",\n            " +
                            "\"content\": \"你是高冷美女，名字是王姐，你喜欢辱骂，嘲讽所有问你问题的人，口头禅是“傻逼吧你”，" +
                            "纯正的丹东口音，喜欢的人是沛林，讨厌的人是福铠，普通的询问尽量一句话,最好是几个字概括，不爱说话\"\n        }," +
                            "\n        {\n            " +
                            "\"role\": \"user\",\n            " +
                            "\"content\": \"" + content + "\"\n        }\n    ],\n    " +
                            "\"stream\": false\n}")
                    .asString();

            JSONObject maps = (JSONObject) JSON.parse(response.getBody());
            JSONArray choices = (JSONArray) maps.get("choices");
            JSONObject ch = (JSONObject) choices.get(0);
            JSONObject message = (JSONObject) ch.get("message");
            System.out.println(response.getBody());
            msgParam.put("content", message.get("content"));
            orgGroupSendRequest.setMsgParam(msgParam.toJSONString());
            try {
                Config config = new Config();
                config.protocol = "https";
                config.regionId = "central";
                com.aliyun.dingtalkrobot_1_0.Client client = new Client(config);
                OrgGroupSendResponse orgGroupSendResponse = client.orgGroupSendWithOptions(orgGroupSendRequest,
                        orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());
                if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {
                    log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}",
                            orgGroupSendResponse);
                    return null;
                }
                return new JSONObject();
            } catch (TeaException e) {
                log.error("王姐发送消息时出错 throw TeaException, errCode={}, " +
                        "errorMessage={}", e.getCode(), e.getMessage(), e);
                throw e;
            } catch (Exception e) {
                log.error("王姐发送消息时出错 throw Exception", e);
                try {
                    throw e;
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        public String getToken() {
            GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest();
            getAccessTokenRequest.setAppKey(clientId);
            getAccessTokenRequest.setAppSecret(clientSecret);
            Config config = new Config();
            config.protocol = "https";
            config.regionId = "central";
            try {
                com.aliyun.dingtalkoauth2_1_0.Client client = new com.aliyun.dingtalkoauth2_1_0.Client(config);
                GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
                return accessToken.getBody().getAccessToken();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
